﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;

namespace NetDon.OA.Portal.Finance
{
    public partial class ConfirmAccountReceipt : NavigationPageBase
    {
        #region Properties

        protected Guid Id
        {
            get { return Parameters.GetGuid("Id"); }
        }

        protected bool IsAccountReceiptCompleted
        {
            set { ViewState["IsAccountReceiptCompleted"] = value; }
            get
            {
                if (ViewState["IsAccountReceiptCompleted"] != null)
                    return Convert.ToBoolean(ViewState["IsAccountReceiptCompleted"].ToString());
                return false;
            }
        }
        private IList<RevenueMachineAccountInvoiceReceiptData> RevenueMachineAccountInvoiceReceipts
        {
            set { ViewState["RevenueMachineAccountInvoiceReceiptData"] = value; }
            get
            {
                if (ViewState["RevenueMachineAccountInvoiceReceiptData"] != null)
                    return ViewState["RevenueMachineAccountInvoiceReceiptData"] as IList<RevenueMachineAccountInvoiceReceiptData>;
                return new List<RevenueMachineAccountInvoiceReceiptData>();
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                CancelButton = btnCancel;
                LoadUserControl();
            }


        }



        public void LoadUserControl()
        {
            var revenueMachineAccountService = ServiceContainer.GetService<IRevenueMachineAccountService>();
            var invoice = revenueMachineAccountService.GetRevenueMachineAccountInvoice(Id);
            this.FormPanelIssuringOrderInfo.DataSource = invoice;
            this.FormPanelIssuringOrderInfo.DataBind();
            IsAccountReceiptCompleted = invoice.IsAccountReceiptCompleted;
            this.lblRouteName.Text = this.GetDictionaryItemName(invoice.RouteTypeId);
            this.txtCustomerName.Text = new CustomerInfoEntity(invoice.CustomerId.Value).CustomerName;
            RevenueMachineAccountInvoiceReceipts = revenueMachineAccountService.GetRevenueMachineAccountInvoiceReceipts(Id).ToList();
            ;
            this.gridOrderDetailList.DataSource = RevenueMachineAccountInvoiceReceipts;
            this.gridOrderDetailList.DataBind();
            
            AddEmptyRevenueMachineAccountInvoiceReceiptAndBind();


            FormPanelRenvenueMachineAccountInvoiceReceipt.Enabled = FormPanelIssuringOrderInfo.Enabled = IsEditable();


        }

        public bool IsEditable()
        {
            if (IsManager()) return true;
            return !IsAccountReceiptCompleted;
        }



        private void AddEmptyRevenueMachineAccountInvoiceReceiptAndBind()
        {
            var tempIssuingOrderDeliveries = RevenueMachineAccountInvoiceReceipts;
            tempIssuingOrderDeliveries.Add(new RevenueMachineAccountInvoiceReceiptData()
            {
                Id = Guid.NewGuid(),
                AreaId = CurrentApplicationContext.CompanyId,
                CreateBy = CurrentApplicationContext.UserId,
                CreatedDate = DateTime.Now,
                LastUpdatedBy = CurrentApplicationContext.UserId,
                RevenueMachineAccountInvoiceId = Id,
            });
            RevenueMachineAccountInvoiceReceipts = tempIssuingOrderDeliveries; //update viewstate
            gridOrderDetailList.DataSource = RevenueMachineAccountInvoiceReceipts;
            gridOrderDetailList.DataBind();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ExtractRevenueMachineAccountInvoiceReceipt();
            //check validation 
            if (this.RevenueMachineAccountInvoiceReceipts.Count(o => !string.IsNullOrWhiteSpace(o.BankNoteNO)) <= 0)
            {
                Alert("请至少输入一笔收款记录！");
                return;
            }
            foreach (var issuingOrderDeliery in this.RevenueMachineAccountInvoiceReceipts)
            {
                if (string.IsNullOrWhiteSpace(issuingOrderDeliery.BankNoteNO)) continue;
                if (!issuingOrderDeliery.AccountsReceiptAmount.HasValue || issuingOrderDeliery.AccountsReceiptAmount.Value <= 0)
                {
                    Alert("请输入收款实收金额");
                    return;
                }
                if(!issuingOrderDeliery.ConfirmAccountsReceiptDate.HasValue)
                {
                    Alert("请输入收款日期");
                    return;
                }
                if (!issuingOrderDeliery.BillOfExchangeDueDate.HasValue)
                {
                    Alert("请输入汇票到期日");
                    return;
                }
            }


            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            var order = service.GetRevenueMachineAccountInvoice(Id);

            order = ExtractRevenueMachineAccountInvoice(order);
            order.TotalAccountReceiptAmount = RevenueMachineAccountInvoiceReceipts.Sum(o => o.AccountsReceiptAmount);
            order.IsAccountReceiptExceptions = !string.IsNullOrWhiteSpace(order.AccountReceiptExceptions) &&
                                             order.AccountReceiptExceptions.Length > 0;
            order.RevenueMachineAccountInvoiceReceipts = RevenueMachineAccountInvoiceReceipts;
            if (order.TotalAccountReceiptAmount > order.InvoiceAmount)
            {
                Alert("总付款金额不可以大于开票金额！");
                return;
            }
            if (order.TotalAccountReceiptAmount == order.InvoiceAmount)
            {
                order.IsAccountReceiptCompleted = true;
                order.ConfirmAccountsReceivableDate = DateTime.Now;
            }
            bool result = service.ModifyRevenueMachineAccountInvoice(order);

            if (result)
            {
                if (order.TotalAccountReceiptAmount == order.InvoiceAmount)
                {
                    Success("保存成功！收款总额和开票总额相等，系统自动设定付款完成！");
                  
                }
                else
                {
                    Success("保存成功！");
                }
                CloseWindow(true);
            }

        }

        protected void gridOrderDetailList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var id = (e.Row.DataItem as RevenueMachineAccountInvoiceReceiptData).Id.ToString();
                var ddlCurrencyType = (e.Row.FindControl("ddlCurrencyType") as DropDownList);

                ddlCurrencyType.SelectedValue =
                    (e.Row.DataItem as RevenueMachineAccountInvoiceReceiptData).CurrencyType.ToString();

                var ddlAccountsReceiptType = (e.Row.FindControl("ddlAccountsReceiptType") as DropDownList);

                ddlAccountsReceiptType.SelectedValue =
                    (e.Row.DataItem as RevenueMachineAccountInvoiceReceiptData).AccountsReceiptType.ToString();
                


                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");


                btnDelete.OnClientClick = string.Format("deleteInvoiceAccountReceipt('{0}');return false;", id);

                var calendarExtender1 = (CalendarExtender)e.Row.FindControl("txtConfirmAccountsReceiptDateCalendarExtender1");
                if (calendarExtender1 != null)
                {
                    calendarExtender1.Format = SystemConfiguration.DateFormat;
                }

                var calendarExtender2 = (CalendarExtender)e.Row.FindControl("txtBillOfExchangeDueDateCalendarExtender1");
                if (calendarExtender2 != null)
                {
                    calendarExtender2.Format = SystemConfiguration.DateFormat;
                }


                var txtConfirmAccountsReceiptDate = (e.Row.FindControl("txtConfirmAccountsReceiptDate") as TextBox);
                if (string.IsNullOrWhiteSpace(txtConfirmAccountsReceiptDate.Text))
                {
                    txtConfirmAccountsReceiptDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                }

                var txtBillOfExchangeDueDate = (e.Row.FindControl("txtBillOfExchangeDueDate") as TextBox);
                if (string.IsNullOrWhiteSpace(txtBillOfExchangeDueDate.Text))
                {
                    txtBillOfExchangeDueDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                }

                if (IsAccountReceiptCompleted)
                {
                    btnDelete.Visible = false;
                }

                var txtBankNoteNO = (TextBox)e.Row.FindControl("txtBankNoteNO");

                txtBankNoteNO.Attributes.Remove("onchange");
                txtBankNoteNO.Attributes.Add("onchange",
                                                   "onChangeDeliveryCode(this,'" + txtBankNoteNO.ClientID +
                                                   "'," + e.Row.RowIndex + ");return false;");
            }

        }
        protected void btnIssuingOrderDeliveryDelete_Click(object sender, EventArgs e)
        {
            var revenueMachineAccountInvoiceReceiptId = hfdIssuingOrderDeliveryId.Value.ToGuid();
            var revenueMachineAccountInvoiceReceipt =
                RevenueMachineAccountInvoiceReceipts.FirstOrDefault(src => src.Id == revenueMachineAccountInvoiceReceiptId);
            if (revenueMachineAccountInvoiceReceipt != null)
            {
                RevenueMachineAccountInvoiceReceipts.Remove(revenueMachineAccountInvoiceReceipt);
                //delete from database
                var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
                service.RemoveRevenueMachineAccountReceipt(revenueMachineAccountInvoiceReceiptId);
            }
            ExtractRevenueMachineAccountInvoiceReceipt();
            gridOrderDetailList.DataSource = RevenueMachineAccountInvoiceReceipts;
            gridOrderDetailList.DataBind();
        }

        private RevenueMachineAccountInvoiceData ExtractRevenueMachineAccountInvoice(RevenueMachineAccountInvoiceData order)
        {

            order.AccountReceiptExceptions = txtAccountReceiptExceptions.Text;
            order.AccountReceiptComments = txtAccountReceiptComments.Text;

            order.AreaId = (CurrentApplicationContext).CompanyId;
            order.LastUpdatedBy = CurrentApplicationContext.UserId;
            order.LastUpdatedDate = DateTime.Now;

            return order;
        }


        private void ExtractRevenueMachineAccountInvoiceReceipt()
        {
            var tempRevenueMachineAccountInvoiceReceipts = new List<RevenueMachineAccountInvoiceReceiptData>();
            foreach (GridViewRow detailRow in gridOrderDetailList.Rows)
            {
                var issuingOrderDeliveryId = gridOrderDetailList.DataKeys[detailRow.RowIndex]["Id"].ToString().ToGuid();
                var issuingOrderDelivery = RevenueMachineAccountInvoiceReceipts.FirstOrDefault(src => src.Id == issuingOrderDeliveryId);

                if (issuingOrderDelivery != null)
                {
                    issuingOrderDelivery.RevenueMachineAccountInvoiceId = Id;


                    issuingOrderDelivery.BankNoteNO = (detailRow.FindControl("txtBankNoteNO") as TextBox).Text;
                    issuingOrderDelivery.CurrencyType = (detailRow.FindControl("ddlCurrencyType") as DropDownList).SelectedValue.ToGuid();
                    issuingOrderDelivery.AccountsReceiptAmount = (detailRow.FindControl("txtAccountsReceiptAmount") as TextBox).Text.ToDecimal();
                    issuingOrderDelivery.AccountsReceiptType = (detailRow.FindControl("ddlAccountsReceiptType") as DropDownList).SelectedValue.ToGuid();

                    var confirmAccountsReceiptDate = (detailRow.FindControl("txtConfirmAccountsReceiptDate") as TextBox).Text;
                    if (!string.IsNullOrWhiteSpace(confirmAccountsReceiptDate))
                    {
                        issuingOrderDelivery.ConfirmAccountsReceiptDate = DateTime.Parse(confirmAccountsReceiptDate);
                    }

                    var txtBillOfExchangeDueDate = (detailRow.FindControl("txtBillOfExchangeDueDate") as TextBox).Text;
                    if (!string.IsNullOrWhiteSpace(txtBillOfExchangeDueDate))
                    {
                        issuingOrderDelivery.BillOfExchangeDueDate = DateTime.Parse(txtBillOfExchangeDueDate);
                    }

                    issuingOrderDelivery.Comments = (detailRow.FindControl("txtComments") as TextBox).Text;

                    issuingOrderDelivery.LastUpdatedBy = CurrentApplicationContext.UserId;
                    issuingOrderDelivery.CreatedDate = issuingOrderDelivery.LastUpdatedDate = DateTime.Now;
                    tempRevenueMachineAccountInvoiceReceipts.Add(issuingOrderDelivery);
                }

            }

            //update viewstate
            RevenueMachineAccountInvoiceReceipts = tempRevenueMachineAccountInvoiceReceipts;
        }

        protected void DateValidator_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            DateTime value;
            e.IsValid = DateTime.TryParse(e.Value, out value);
        }



        public void txtDeliveryOrderCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(HiddenDeliveryCode.Value))
            {
                ExtractRevenueMachineAccountInvoiceReceipt();
            }

            AddEmptyRevenueMachineAccountInvoiceReceiptAndBind();
            ;
        }






    }
}